package cn.qyd.leecode;

/**
 * @author 邱运铎
 * @date 2024-04-14 2:28
 */
class MyHashSet {
    private static final int BASE = 32;
    private int[] bitMap;

    public MyHashSet() {
        //1000000 / 32 = 31250
        bitMap = new int[31251];
    }

    public void add(int key) {
        setBitMap(key / BASE, key % BASE, true);
    }

    public void remove(int key) {
        setBitMap(key / BASE, key % BASE, false);
    }

    public boolean contains(int key) {
        return getBitMap(key / BASE, key % BASE);
    }

    private boolean getBitMap(int num, int offset) {
        return (bitMap[num]>>offset&1) == 1;
    }

    public int[] getBitMap() {
        return bitMap;
    }
    /** int 类型 32位，
     * 对 32 取模后是同一个下标 i 的初始值为 0 ： 即bitMap[i] = 0
     * 这里让每一个二进制位代表对32取模是相同的不同数字存在。
     * 例如 bitMap[1] = 7, 00...0111 -> 代表 32 33 34 存在
     */
    private void setBitMap(int num, int offset, boolean isAdd) {
        if (isAdd) {
            bitMap[num] = bitMap[num] | (1 << offset);
        } else {
            bitMap[num] = bitMap[num] & (~(1 << offset));
        }
    }

    public static void main(String[] args) {
        MyHashSet myHashSet = new MyHashSet();
        myHashSet.add(32);
        System.out.println(myHashSet.getBitMap()[1]);
        myHashSet.add(33);
        System.out.println(myHashSet.getBitMap()[1]);
        myHashSet.add(34);
        System.out.println(myHashSet.getBitMap()[1]);
        myHashSet.add(64);
        System.out.println(myHashSet.getBitMap()[2]);

        System.out.println(myHashSet.contains(32));
        System.out.println(myHashSet.contains(64));
    }
}
